<?php

namespace App\Supports\WithdrawFreelance;

use Exception;

use Carbon\Carbon;
use App\Models\User;
use App\Models\Withdraw;
use App\Models\Freelance;
use App\Jobs\UserWithdrawJob;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use App\Supports\Withdraw\WithdrawBase;
use Illuminate\Validation\ValidationException;
use App\Supports\WithdrawFreelance\LinkInq\LinkInq;
use App\Supports\WithdrawFreelance\GaoDeng\GaoDeng;

class FreelanceApply  extends WithdrawBase
{
	
	public function auth(User $user)
	{
		
		try {

			$channel = WithdrawBase::getChannel();
			if($channel == 'linkINQ'){
				if ($user->freelance) {
					abort(400, '用户已认证');
				}

				if (Freelance::where('id_no',request('id_no'))->first()) {
					abort(400, '身份证已被使用');
				}

				$freelance = app(LinkInq::class, ['user' => $user]);
				$user = $freelance->register();
				return $user;

			}elseif($channel== 'gaodeng'){

				$freelance = app(GaoDeng::class, ['user' => $user]);
				$user = $freelance->register();
				return $user;

			}
			
		} catch (Exception $exception) {
			throw ValidationException::withMessages(['err' => $exception->getMessage()]);
		}
	}

	public function verify()
	{
		if (! $this->isWithdrawOpened()) {
			throw ValidationException::withMessages(['err' => '平台尚未开放提现功能']);
		}
		/*if ($this->isAppliedToday()) {
			throw ValidationException::withMessages(['err' => "每日只可提现1次"]);
		}*/
		/*if (! $this->isAccountBound()) {
			throw ValidationException::withMessages(['err' => "提现账号未绑定"]);
		}*/
		if (! $this->isMethodSupport()) {
			throw ValidationException::withMessages(['err' => "平台不支持 '{$this->targetMethod}' 提现方式"]);
		}
		if (! $this->isMultipleMatched()) {
			throw ValidationException::withMessages(['err' => "提现金额必须是 '{$this->withdrawMultiple()}' 的倍数"]);
		}
		if (! $this->isLowestAmountMatched()) {
			throw ValidationException::withMessages(['err' => "提现金额必须大于 '{$this->getAllowedLowestAmount()}'"]);
		}
		if (! $this->isHighestAmountMatched()) {
			throw ValidationException::withMessages(['err' => "提现金额必须小于 '{$this->getAllowedHighestAmount()}'"]);
		}
		if (! $this->isUserBalanceEnough()) {
			throw ValidationException::withMessages(['err' => "可提现余额不足"]);
		}
	}
	
	public function apply()
	{
		$lock = Cache::lock('freelance', 5);
		
		if (! $lock->get()) {
			throw ValidationException::withMessages(['err' => '操作过于频繁，请稍后再试！']);
		}
		
		DB::transaction(function () {
			
			$this->verify();
			$channel = WithdrawBase::getChannel();
			if($channel == 'linkINQ'){
				$freelance = app(LinkInq::class, ['user' => $this->targetUser]);
				$user = $freelance->withdraw($this->chargeFee,$this->actualAmount);

			}elseif($channel == 'gaodeng'){

				$freelance = app(GaoDeng::class, ['user' => $this->targetUser]);
				$user = $freelance->withdraw();
			}
			
		});
		
		$lock->release();
	}

	public function notify()
	{
		$content = request('biz_content');

		if(!$content){
			throw ValidationException::withMessages(['err' => '无回调数据']);
		}

		$content = json_decode($content,true);
		
		$withdraw = Withdraw::where('plat_batch_no',$content['platBatchNo'])->where('status','pending')->first();
		
		if(!$withdraw){
			throw ValidationException::withMessages(['err' => '未查找到平台批次号']);
		}



		if($content['batchStatus'] == 1){
			$withdraw->update([
				'actual_amount' => $content['batchAmt'],
				'paid_at' => Carbon::now(),
				'status' => 'paid',
			]);

			$data = ['withdraw_id' => $withdraw->id];
			account('balance', $withdraw->user)->minusWithdrawPrincipal($content['batchAmt'], $data);
			account('balance', $withdraw->user)->minusWithdrawCharge($withdraw['charge_amount'], $data);

		}else{
			$withdraw->update([
				'status' => 'failed',
				'remark' => $content['failList'][0]['errorMsg']
			]);

		}
		
	}


	public function gdNotify()
	{

		$data = request('data');
		if(!$data){
			throw ValidationException::withMessages(['err' => '回调数据为空']);
		}

		$this->config = config('gaodeng');
		$this->appkey = $this->config['appkey'];
		$this->appsecret = $this->config['appsecret'];
		$this->aesIV = $this->config['aesIV'];
		$data =  openssl_decrypt($data,'AES-256-CBC',$this->appsecret,0,$this->aesIV);
		if(!$data){
			throw ValidationException::withMessages(['err' => '回调数据有误']);
		}

		$data = json_decode($data,true);
		if(is_array($data)){
			$data = $data[0];
		}

		$withdraw = Withdraw::where('plat_batch_no',$data['order_random_code'])->first();
		
		if(!$withdraw){
			throw ValidationException::withMessages(['err' => '未查找到单号']);
		}


		if($data['status'] == 1000){
			$withdraw->update([
				'charge_amount' => $data['service_amount'],
				'actual_amount' => $data['settle_amount'],
				'target_amount' => $data['total_money'],
				'paid_at' => Carbon::now(),
				'status' => 'paid',
			]);

			$id_arr = ['withdraw_id' => $withdraw->id];
			account('balance', $withdraw->user)->minusWithdrawPrincipal($data['settle_amount'], $id_arr);
			account('balance', $withdraw->user)->minusWithdrawCharge($data['service_amount'], $id_arr);

		}elseif($data['status'] == 1004){
			$user = User::find($withdraw->user_id);
			$freelance = app(GaoDeng::class, ['user' => $user])->refund($data['order_random_code']);
			$withdraw->update([
				'status' => 'failed',
			]);

		}
		
	}
}
